﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccess.SingleSignOn;
using Single_SignOn.Areas.PDA.Models;
using Single_SignOn.Attributes;
using Single_SignOn.ResX;

namespace Single_SignOn.Areas.PDA.Controllers
{
    public class ChangeSwordController : Controller
    {
        //
        // GET: /IE5/ChangeSword/
        public AuthenConnection oAuth;

        public ActionResult Index()
        {
            ChangePassword models = new ChangePassword();

            if (Request.QueryString["Username"] != null)
                models.UserName = Request.QueryString["Username"];

            return View("Index", models);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [MultipleButton(Name = "State", Argument = "Save")]
        public ActionResult Confirm(ChangePassword models)
        {
            oAuth = new AuthenConnection();

            try
            {
                if (oAuth.pullUserProfile(models.UserName).Rows.Count <= 0)
                {
                    ModelState.AddModelError("CheckUsername", ResourceTools.GetResource("Resource", "CheckUsername"));
                }
                else
                {
                    if (oAuth.pullUserProfile(models.UserName, models.OldPassword)
                        .Rows.Count <= 0)
                    {
                        ModelState.AddModelError("CheckOldPassword", ResourceTools.GetResource("Resource", "CheckOldPassword"));
                
                    }
                    else
                    {
                        if (oAuth.upChangePassword(models.UserName, th.co.homepro.Utility.zEncrypt(models.NewPassword, WebConfig.Encryptkey, WebConfig.EncryptValue)))
                        {
                            return RedirectToAction("Index", "Login", new { Username = models.UserName });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("MessageException", ex.Message);
            }
            return View("Index", models);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [MultipleButton(Name = "State", Argument = "Cancel")]
        public ActionResult Back(ChangePassword models)
        {
            return RedirectToAction("Index", "Login", new { Username = models.UserName });
        }
    }
}
